
var PlayLayer = cc.Layer.extend({
        bgSprite : null, 
    score : 0,
    timeout : 10,            //游戏时间
    x_count : 4,
    y_count : 5,
    margin_top : 50,        //游戏区域上边距
    margin_lr : 10,         //游戏区域左右边距
    icon_size : null,       //图标大小
    start_x : null,         //游戏区域开始X
    start_y : null,         //游戏区域开始Y
    map_icon : new Map(),   //创建icon map
    replace_time : 0.1,        //交换图标时间
    can_move : 1,      //当前是否可以移动
    onEnter : function() {
            this._super();
            this.initIcons();
    },
    ctor:function(){
                this._super();

                var size = cc.winSize;

                //添加背景
                this.bgSprite = new cc.Sprite(res.bg);
                this.bgSprite.attr({
                        x: size.width / 2,
                        y: size.height / 2,
                });

                this.addChild(this.bgSprite, 0);


                //添加倒计时
                this.schedule(this.onTimer, 1, this.timeout, 0);

                //添加分数
                this.scoreLabel = new cc.LabelTTF("score:0", "", 20);
                this.scoreLabel.attr({
                        x: size.width - 60,
                        y: size.height  - 20,
                        color: cc.color(0, 0, 255),
                });
                this.addChild(this.scoreLabel, 6);

                //添加倒计时
                this.timeoutLabel = new cc.LabelTTF("" + this.timeout, "", 30);
                this.timeoutLabel.attr ({
                        x: 30,
                        y: size.height - 20,
                        color: cc.color(0, 0, 255),
                });
                this.addChild(this.timeoutLabel, 6);

                action_list = [];

                //添加logo
                var logo = new cc.Sprite(res.logo);
                logo.attr({
                        x: size.width - 35,
                        y: 15,
                });
                logo.setScale(0.5);
                this.addChild(logo, 10);


                /*******************************************************/
                //添加进度条
                /*
                var progress = new cc.ProgressTimer();
                progress.attr({
                        x: 15,
                        y: size.height - 30,
                });
                this.addChild(progress, 10);
                */



                /*******************************************************/
                //添加礼包图标
                var gift_icon = new cc.Sprite(res.gift);
                gift_icon.attr({
                        x: 30,
                        y: 20, 
                });
                gift_icon.setScale(0.3);
                this.addChild(gift_icon, 10);

                for(var i = 0; i < 3; i ++) {
                        var gift_sp = new cc.Sprite(icons_file[i]);
                        gift_sp.setScale(0.25);
                        gift_sp.attr({
                                x: 65 + i * 25, 
                                y: 20 
                        });
                        this.addChild(gift_sp, 10);
                }


                return true;
    },

    onTimer : function() {
            if (this.timeout == 0)
            {

                    //游戏结束了
                    var gameOver = new cc.LayerColor(cc.color(0,0,0,220));
                    var size = cc.winSize;
                    var titleLabel = new cc.LabelTTF("游戏结束!", "Arial", 38);
                    titleLabel.attr({
                            x:size.width / 2 ,
                            y:size.height -  60,
                            color: cc.color(255,255,0),
                    });
                    gameOver.addChild(titleLabel, 10);


                    var touchlistener = cc.EventListener.create({
                            event : cc.EventListener.TOUCH_ONE_BY_ONE,
                            swallowTouches: true,
                            onTouchBegan : function(touch, event) {
                                    console.log("gameOver onTouchBegan...");
                                    return true;        
                            },
                    });

                    /***********************************************************/
                    //展示结果页
                    var resultLabel = new cc.LabelTTF("999分,击败了98%的网友！", 
                                     "", 20,cc.size(size.width - 50, 200), cc.TEXT_ALIGNMENT_CENTER);  
                    resultLabel.attr({
                            x: size.width / 2,
                            y: size.height - 200,
                            color : cc.color(255,0,0),
                    });
                    gameOver.addChild(resultLabel, 10);



                    if (cc.random0To1() > 0.5) {
                            /*************************/
                            //展示单个应用
                            var oneAppLabel = new cc.LabelTTF("您和天天酷跑最有眼缘，点击进入应用宝下载试玩。", 
                                            "", 15,cc.size(size.width - 50, 200), cc.TEXT_ALIGNMENT_LEFT);  
                            oneAppLabel.attr({
                                    x: size.width / 2,
                                    y: size.height - 250,
                                    color : cc.color(255,255,0),
                            });
                            gameOver.addChild(oneAppLabel, 10); 

                            var game_icon = new cc.Sprite(icons_file[0]);
                            game_icon.attr({
                                    x: size.width / 2 - 50,
                                    y: size.height - 250,
                            });
                            gameOver.addChild(game_icon, 11);

                            var game_label = new cc.LabelTTF("XXX好友在玩\n策略类 80M\n进入应用宝下载", "", 15, cc.size(150, 100), cc.TEXT_ALIGNMENT_LEFT);
                            game_label.attr({
                                    x: size.width / 2 + 80,
                                    y: size.height - 270,
                            });
                            gameOver.addChild(game_label, 11);
                            /*************************/
                    }
                    else {
                            /*************************/
                            //展示应用排行列表
                            for(var i = 0; i < 4; i ++){
                                    var img = new cc.Sprite(icons_file[i+1]);
                                    img.setScale(0.4);
                                    img.attr({
                                            x: size.width / 2 - 100,
                                            y: size.height - 150 - i * 45, 
                                    });
                                    gameOver.addChild(img, 11);

                                    var label = new cc.LabelTTF("消除"+ (93 - i * i) + "次  XXX应用 XX好友在玩", "", 10);
                                    label.attr({
                                            x: size.width / 2 + 30,
                                            y: size.height - 150 - i * 45,
                                    });
                                    gameOver.addChild(label);
                            } 
                            /*************************/
                    }
                    

                    //添加礼包图标
                    gift_label = new cc.LabelTTF("如下游戏有礼包可领，点击进入应用宝领取礼包：", "", 10);
                    gift_label.attr({
                            x: size.width / 2,
                            y: 140,  
                            color: cc.color(255,0,0),

                    });
                    gameOver.addChild(gift_label, 11);

                    //添加礼包图标
                    var gift_icon = new cc.Sprite(res.gift);
                    gift_icon.attr({
                            x: 60,
                            y: 105, 
                    });
                    gift_icon.setScale(0.3);
                    gameOver.addChild(gift_icon, 10);



                    for(var i = 0; i < 3; i ++) {
                            var gift_sp = new cc.Sprite(icons_file[i]);
                            gift_sp.setScale(0.25);
                            gift_sp.attr({
                                    x: 110 + 28*i, 
                                    y: 105,
                            });
                            gameOver.addChild(gift_sp, 10);
                    }



                    /***********************************************************/
                   
                    cc.eventManager.addListener(touchlistener, gameOver); 


                    /***************************************************/
                    //重试菜单
                    var TryAgainItem = new cc.MenuItemFont(
                                    "重试",
                                    function () {
                                            var s = new PlayScene();
                                            s.x_count = this.x_count;
                                            s.y_count = this.y_count;
                                            cc.director.runScene(s);
                                    }, this);
                    TryAgainItem.attr({
                            x: size.width/2 + 50,
                            y: 50, 
                            anchorX: 0.5,
                            anchorY: 0.5
                    });

                    /***************************************************/
                    //回退菜单
                    var BackItem = new cc.MenuItemFont(
                                    "返回",
                                    function() { 
                                            cc.director.popScene();
                                    }, this);
                    BackItem.attr({
                            x: size.width / 2 - 50,
                            y: 50,
                            anchorX: 0.5,
                            anchorY: 0.5,
                    });

                    var menuItems = [TryAgainItem, BackItem/*, ShareItem*/];
                    var menu = new cc.Menu(menuItems);
                    menu.x = 0;
                    menu.y = 0;
                    menu.setColor(cc.color(255,0,0));


                    gameOver.addChild(menu, 1);
                    //添加浮层
                    this.getParent().addChild(gameOver);

                    this.unschedule(this.timer);
                    return ;
            }

            this.timeout  -= 1;
            this.timeoutLabel.setString("" + this.timeout);
            
    },

    replace : function(x1, y1, x2, y2) { 
            var start_index = this.getIndexByXY(x1, y1);
            var end_index = this.getIndexByXY(x2,y2); 

            var pos_org = this.getPosXY(x1, y1);    //源位置
            var pos_tar = this.getPosXY(x2, y2);    //目标位置

            var org = this.map_icon[start_index];        //源对象
            var tar = this.map_icon[end_index];          //目标对象

            //this.can_move = 0;  //锁定移动

            //定义源对象动画
            var moveActionOrg = cc.MoveTo.create(this.replace_time, cc.p(pos_tar.x, pos_tar.y));
            var action_seq = new cc.Sequence([moveActionOrg,new cc.CallFunc( function (sender) {
                    console.log("action_over"); 
                    this.can_move = 1;        //释放锁定

            }, this)] );

            org.runAction(action_seq);


            //定义目标对象动画
            var moveActionTar = cc.MoveTo.create(this.replace_time, cc.p(pos_org.x, pos_org.y));
            tar.runAction(moveActionTar);

            org.index_x = x2;
            org.index_y = y2;

            tar.index_x = x1;
            tar.index_y = y1;

            this.map_icon[start_index] = tar;
            this.map_icon[end_index] = org;
    },

    replaceLeft : function (x1, y1) {
           if (x1 > 0) {
                   this.replace(x1,y1, x1-1, y1); 
                   return 0;
           }
           else{
                   return 1;

           };
    },
    replaceRight : function (x1, y1) {
           if (x1 < this.x_count - 1) {
                   this.replace(x1,y1, x1 + 1, y1); 
                   return 0;
           }
           else{
                   return 1;

           };
    },
    replaceTop : function (x1, y1) {
           if (y1 < this.y_count -1) {
                   this.replace(x1,y1, x1, y1 + 1); 
                   return 0;
           }
           else{
                   return 1;

           };
    },
    replaceDown : function (x1, y1) {
           if (y1 > 0) {
                   this.replace(x1,y1, x1, y1 - 1); 
                   return 0;
           }
           else{
                   return 1;

           };
    },

    goBack : function(x, y) {
            //说明移动距离还是不够的,需要打回去
            var pos_org = this.getPosXY(x, y);
            var moveAction = cc.MoveTo.create(this.replace_time, cc.p(pos_org.x, pos_org.y));
            var call_back = new cc.CallFunc(
                            function (sender) {
                                    console.log("action_over"); 
                                    this.can_move = 1;        //释放锁定

                            }, this);

            var key = this.getIndexByXY(x, y);
            var target = this.map_icon[key];
            target.runAction(new cc.Sequence([moveAction, call_back]));
            target.addTouchEventListense();
    },


    //根据XY编号得到其坐标位置
    getPosXY : function(x, y) {
            var pos_x = this.start_x + x * this.icon_size;
            var pos_y =  this.start_y + y * this.icon_size;
            return {x : pos_x, y: pos_y};
    },

    getIndexByXY : function(x, y){
            return y * this.x_count + x;
    },

    initIcons : function() {
            //首先计算每个图标的大小
            var size = cc.winSize;
            this.icon_size = Math.round((size.width - 2 * this.margin_lr) / this.x_count); 
            
            this.start_x = this.margin_lr + Math.round(this.icon_size / 2); 
            this.start_y = size.height - this.margin_top - this.icon_size * this.y_count + Math.round(this.icon_size / 2);

            //下面开始生成图标方阵
            for(var i = 0; i < this.y_count; i ++){
                    for(var j = 0; j < this.x_count; j ++) {
                            var index = Math.round(cc.random0To1() * (icons_file.length - 1));
                            var icon_file = icons_file[index];
                            console.log(index + " " + icon_file);
                            var key = this.getIndexByXY(j, i);
                            var icon_sprite = new IconSprite(icon_file);
                            icon_sprite.setScale((this.icon_size - 6) / 92);
                            var pos = this.getPosXY(j, i);
                            icon_sprite.attr({
                                    x: pos.x, 
                                    y: pos.y,
                            });
                            icon_sprite.index_x = j;
                            icon_sprite.index_y = i;

                            icon_sprite.index_x = j;
                            icon_sprite.index_y = i;

                            this.addChild(icon_sprite, 10);
                            this.map_icon[key] = icon_sprite;

                            var action_fade_in = cc.FadeIn.create(10);
                            icon_sprite.runAction(action_fade_in);
                    }
            }

    },
    
});


var PlayScene = cc.Scene.extend ({
        x_count: 4,
        y_count : 5,
        replace_time : 0.1, 
        onEnter:function() {
                this._super();
                var layer = new PlayLayer();
                layer.x_count = this.x_count;
                layer.y_count = this.y_count;
                layer.replace_time = this.replace_time; 
                this.addChild(layer); 
        }
});
